<template>
  <div class="defectTotal">
    <userHeader/>
    <div class="breadClum">
      <span>
           <router-link :to="{path:'/pageIndex'}"> <a class="bread1">当前位置：首页  >  </a></router-link>
           <router-link :to="{path:'/query'}"><a class="bread2">综合查询  ></a></router-link>
         <a class="bread2">缺陷统计查询</a>
      </span>
    </div>
    <div class="navList">
      <!--评价企业-->
      <el-dropdown trigger="click"
                   style="cursor:pointer;background: #8cc34b;padding:10px 24px;color:#fff;border-radius:4px;text-align: center;"
                   @command="handleCommentCompany">
          <span class="el-dropdown-link">
            {{commentCompany}}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
        <el-dropdown-menu slot="dropdown" style="padding: 0 10px;height: 300px;overflow-y: scroll">
          <el-dropdown-item v-for="item in companyList" :command="item" :key="item.company_id">{{item.company_name}}</el-dropdown-item>
          <el-dropdown-item v-if="companyList.length==0">暂无数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <!--评价期间-->
      <el-dropdown trigger="click"
                   style="cursor:pointer;background: #8cc34b;padding:10px 24px;color:#fff;border-radius:4px;text-align: center;"
                   @command="setEvaluationPeriod">
          <span class="el-dropdown-link">
            {{evaluationPeriodSelect}}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
        <el-dropdown-menu slot="dropdown" style="padding: 0 10px;height: 300px;overflow-y: scroll">
          <el-dropdown-item v-for="item in evaluationPeriodList" :command="item"
                            :key="item.evaluation_period">{{item.evaluation_period}}
          </el-dropdown-item>
          <el-dropdown-item v-if="evaluationPeriodList.length==0">暂无数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>


      <!--评价类型-->
      <el-dropdown trigger="click"
                   style="cursor:pointer;background: #8cc34b;padding:10px 24px;color:#fff;border-radius:4px;text-align: center;"
                   @command="handleCommentType">
          <span class="el-dropdown-link">
            {{commentType}}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
        <el-dropdown-menu slot="dropdown" style="padding: 0 10px;height: 300px;overflow-y: scroll">
          <el-dropdown-item v-for="item in commentTypeList" :command="item" :key="item.evaplan_type_id">{{item.evaplan_type_name}}</el-dropdown-item>
          <el-dropdown-item command="none" v-if="commentTypeList.length==0">暂无数据</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <div class="navListRight">
         <el-date-picker
           v-model="period"
           type="daterange"
           style="width:250px;height:40px;"
           start-placeholder="开始日期"
           end-placeholder="结束日期"
           :default-time="['00:00:00', '23:59:59']">
          </el-date-picker>
          <el-button @click="downLoadFile" :loading="downloadLoading" class="download-file" style="" type="primary" icon="el-icon-download" size="mini"></el-button>
      </div>
    </div>
    <el-table
      :data="commentTableData.defect_list"
      stripe
      show-summary
      sum-text="合计"
      v-loading="loading"
      :summary-method="getTotal"
    >
      <el-table-column
        prop="process_num"
        label="编号"
      >
      </el-table-column>
      <el-table-column
        prop="process_name"
        label="评价流程"
      >
      </el-table-column>
      <el-table-column
        prop="controlpoint_num"
        label="控制点"
      >
      </el-table-column>
      <el-table-column
        prop="defects_num"
        label="缺陷数量"
      >
      </el-table-column>
      <el-table-column
        label="缺陷来源">
        <el-table-column
          prop="design_defect_num"
          label="设计缺陷">
        </el-table-column>
        <el-table-column
          prop="execute_defect_num"
          label="执行缺陷">
        </el-table-column>
        <el-table-column
          prop="design_execute_num"
          label="设计和执行缺陷">
        </el-table-column>
      </el-table-column>
      <el-table-column
        label="缺陷性质">
        <el-table-column
          prop="general_defect_num"
          label="一般缺陷">
        </el-table-column>
        <el-table-column
          prop="crucial_defect_num"
          label="重要缺陷">
        </el-table-column>
        <el-table-column
          prop="fatal_defect_num"
          label="重大缺陷">
        </el-table-column>
      </el-table-column>
      <el-table-column
        prop="total_standard_score"
        label="标准分值"
      >
      </el-table-column>
      <el-table-column
        prop="total_evaluation_score"
        label="评价分值"
      >
      </el-table-column>
      <el-table-column
        prop="defects_rate"
        label="比率(%)"
      >
      </el-table-column>
    </el-table>

    <!--分页器-->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="page"
        :page-size="limit"
        background
        layout="prev, pager, next, jumper"
        :page-count="pages">
      </el-pagination>
    </div>

  </div>
</template>
<script>
  import userHeader from '@/components/header.vue'
  import {mapState} from 'vuex';
  export default ({
    data() {
      return {
        limit: 10,
        page: 1,
        pages:1,
        period:'',
        commentCompany: "评价企业",
        company_id:'',
        companyList:[],
        commentPeriod: '',//评价期间的时间段
        evaluation_period:'',
        evaluationPeriodSelect:'评价期间',
        evaluationPeriodList:[],
        commentType: "评价类型",
        evaplan_type_id:'',
        commentTypeList:[],
        commentTableData: {},
        downloadLoading:false,
        loading:true,
      }
    },
    components: {
      userHeader,
    },
    created() {
      this.getCompanyList();
      this.getDefectTotalData(this.company_id,this.evaluation_period,this.evaplan_type_id,this.limit, this.page)
    },
    methods: {
      //评价企业
      handleCommentCompany(command) {
        console.log(command)
          this.loading=true;
        //当在选择公司 查看了数据之后  切换公司时  需将上一次 的 各个数据还原
        this.evaluation_period='';
        this.evaplan_type_id='';
        this.process_id ='';
        this.evaluationPeriodSelect ='评价期间';
        this.commentType = "评价类型";
        this.progressType='评价流程';

        if(command=='none' ||command.company_id == this.company_id){
          return false
        }
        this.company_id = command.company_id == "all" ? '':command.company_id;
        this.commentCompany = command.company_name;

        this.getCommentTypeList(this.company_id,this.evaluation_period).then(res=>{
          console.log(res)
          if(res.data.code == 0){
            this.commentTypeList = [...res.data.data,{
              "evaplan_type_id": "all",
              "evaplan_type_name": "所有",
              "start_time": "",
              "end_time": "",
              "company_id": "",
              "bl_year_evaluate": "",
              "current_time": "",
              "evaluation_period": "",
              "numrow": ""
            }]
          }

        })

        this.getCompanyEvaluationPeriod(command.company_id).then(res => {
          console.log(res.data.data)
          if (res.data.code == 0) {
            this.evaluationPeriodList = [...res.data.data,{evaluation_period: "所有"}]
          }
        }).then(()=>{
          this.getCommentTypeList(this.company_id,this.evaluation_period).then(res=>{
            console.log(res)
            if(res.data.code == 0){
              this.commentTypeList = [...res.data.data,{
                "evaplan_type_id": "all",
                "evaplan_type_name": "所有",
                "start_time": "",
                "end_time": "",
                "company_id": "",
                "bl_year_evaluate": "",
                "current_time": "",
                "evaluation_period": "",
                "numrow": ""
              }]
            }

          }).then(()=>{
            this.getDefectTotalData(this.company_id,this.evaluation_period,this.evaplan_type_id,this.limit, this.page)
          })


        })
      },
      //评价期间
      setEvaluationPeriod(command){
        if(command == 'none'||command.evaluation_period==this.evaluation_period){
          return false
        }
        this.evaluation_period = command.evaluation_period =='所有' ? '':command.evaluation_period;
        this.evaluationPeriodSelect = command.evaluation_period;
        this.commentType='评价类型';
        this.loading =true;
        this.evaplan_type_id='';
        this.getCommentTypeList(this.company_id,this.evaluation_period).then(res=>{
          console.log(res)
          if(res.data.code == 0){
            this.commentTypeList = [...res.data.data,{
              "evaplan_type_id": "all",
              "evaplan_type_name": "所有",
              "start_time": "",
              "end_time": "",
              "company_id": "",
              "bl_year_evaluate": "",
              "current_time": "",
              "evaluation_period": "",
              "numrow": ""
            }]
          }

        }).then(()=>{
          this.getDefectTotalData(this.company_id,this.evaluation_period,this.evaplan_type_id,this.limit, this.page)
        })


      },
      //评价类型选择
      handleCommentType(command) {
        console.log(command)
        console.log(command)
        this.loading=true;
        if(command == 'none'||command.evaplan_type_id==this.evaplan_type_id){
          return false
        }
        this.evaplan_type_id =  command.evaplan_type_id =='all' ? '':command.evaplan_type_id;
        this.commentType = command.evaplan_type_name;
        this.getDefectTotalData(this.company_id,this.evaluation_period,this.evaplan_type_id,this.limit, this.page)


      },
      //获取公司列表
      getCompanyList() {
        this.axios.get('/api/v1/enquiry/companyflat')
          .then((res) => {
            var companyList = [];
            if (res.data.code == 0) {
              console.log((res.data.data))
              companyList = this.formatSonCompany(res.data.data);
              this.companyList = [...companyList, {
                company_id: "all",
                company_level: "1",
                company_name: "所有",
                company_num: "",
                company_pid: "",
                company_state: "",
                current_time: "",
                evaluate_section: "",
                numrow: "",
                son_company: [],
              }]
              console.log(this.companyList)
            }
          })
      },
      //将公司列表树状结构转化为数组
      formatSonCompany(data) {
        var temp = [], list = [];

        function copySonCompany(obj) {
          temp = [...temp, obj]
          if (obj.son_company.length > 0) {
            obj.son_company.forEach(element => {
              copySonCompany(element)
            })
          }
          return temp
        }

        data.forEach(el => {
          list = [...list, ...copySonCompany(el)]
        })
        return list
      },
      getDefectTotalData(company_id,evaluation_period,evaplan_type_id,limit, page) {
        this.axios.get('/api/v1/enquiry/defectstatistics?company_id='+company_id+'&evaluation_period='+evaluation_period+'&evaplan_type_id='+evaplan_type_id+'&limit=' + limit + '&page=' + page).then(res => {
          if (res.data.code == 0) {
            console.log(res.data.data)
            this.commentTableData = res.data.data
            this.page = res.data.pagination.page;
            this.limit = res.data.pagination.limit;
            this.pages =  res.data.pagination.pages;
            this.loading =false;
          } else {
            this.$alert(res.data.message, "提示")
          }

        });
      },
      getTotal(param) {
        console.log(param)
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          switch (column.property) {
            case "process_name":
              sums[index] = this.commentTableData.process_total;
              break;
            case "controlpoint_num":
              sums[index] = this.commentTableData.controlpoint_total;
              break;
            case "defects_num":
              sums[index] = this.commentTableData.defects_total;
              break;
            case "design_defect_num":
              sums[index] = this.commentTableData.design_defect_total;
              break;
            case "execute_defect_num":
              sums[index] = this.commentTableData.execute_defect_total;
              break;
            case "design_execute_num":
              sums[index] = this.commentTableData.design_execute_total;
              break;
            case "general_defect_num":
              sums[index] = this.commentTableData.general_defect_total;
              break;
            case "crucial_defect_num":
              sums[index] = this.commentTableData.crucial_defect_total;
              break;
            case "fatal_defect_num":
              sums[index] = this.commentTableData.fatal_defect_total;
              break;
            case "total_standard_score":
              sums[index] = this.commentTableData.standard_score_total;
              break;
            case "total_evaluation_score":
              sums[index] = this.commentTableData.evaluation_score_total;
              break;
            case "defects_rate":
              sums[index] = this.commentTableData.defects_rate_total;
              break;
            default:
              sums[index] = "--";
              break;
          }
        });
        return sums;
      },
      handleCurrentChange(val) {
        console.log(val);
        this.page = val;
        this.getDefectTotalData(this.company_id,this.evaluation_period,this.evaplan_type_id,this.limit, this.page)
        // this.getTableDataByCondition(this.handleStaffId,this.operationPeriodFormat,this.limit,this.currentPage)
      },
      downLoadFile(){
        if(this.commentTableData.defect_list.length>0){
          this.downloadLoading = true
          import('../utils/export2Excel').then(excel => {
            console.log(1111)
            const filterVal = ['process_num', 'process_name', 'controlpoint_num', 'defects_num', 'design_defect_num','execute_defect_num','design_execute_num','general_defect_num','crucial_defect_num','fatal_defect_num','total_standard_score','total_evaluation_score','defects_rate']
            // const filterVal = ['编号', '评价流程', '控制点', '控制数量', '设计缺陷','执行缺陷','设计和执行缺陷','一般缺陷','重要缺陷','重大缺陷','标准分值','设计分值','比率(%)']
            const tHeader = ['编号', '评价流程', '控制点', '控制数量', '设计缺陷','执行缺陷','设计和执行缺陷','一般缺陷','重要缺陷','重大缺陷','标准分值','设计分值','比率(%)']


            //此处为 合计的数据
            const lastColumn = {
              process_num: "合计",
              process_name: this.commentTableData.process_total,
              controlpoint_num: this.commentTableData.controlpoint_total,
              crucial_defect_num: this.commentTableData.crucial_defect_total,
              current_time: parseInt(new Date())/1000,
              defects_num: this.commentTableData.defects_total,
              defects_rate: this.commentTableData.defects_rate_total,
              design_defect_num: this.commentTableData.execute_defect_total,
              design_execute_num: this.commentTableData.design_execute_total,
              element_id: "",
              execute_defect_num: this.commentTableData.execute_defect_total,
              fatal_defect_num: this.commentTableData.fatal_defect_total,
              general_defect_num: this.commentTableData.general_defect_total,
              is_hascontrolpoint: "",
              process_id: "",
              process_pid: "0",
              total_evaluation_score: this.commentTableData.evaluation_score_total,
              total_standard_score: this.commentTableData.standard_score_total,
              user_id: "",
            }

            const list = [...this.commentTableData.defect_list,lastColumn]
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data:data,
              filename:"缺陷统计表（第"+this.page+"页）",
              autoWidth: true,
              bookType: "xlsx"
            })
            this.downloadLoading = false

          })
        }else {
          this.$alert("表格无数据，无法下载","提示")
        }

      },
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			},
      //获取公司的评价期间列表
      getCompanyEvaluationPeriod(company_id) {
        return this.axios.get('/api/v1/flow/controlindicators?company_id=' + company_id)
      },
      //获取评价类型列表
      getCommentTypeList(company_id,evaluation_period){
        // /api/v1/enquiry/evaplantypequery?company_id=5&evaluation_period=2019
        return this.axios.get('/api/v1/enquiry/evaplantypequery?company_id='+company_id+'&evaluation_period='+evaluation_period)
      }

    },
    computed: {
      ...mapState({
        user_id: state => state.app.loginState.user_id || sessionStorage.getItem('user_id'),
        height:state=>sessionStorage.getItem('height')||state.app.height,
      }),
    }
  })
</script>
<style scoped="">
  .defectTotal {
    width: 100%;
    height: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    padding: 10px;
  }

  .defectTotal .navList {
    padding-bottom: 12px;
    margin-bottom: 12px;
  }

  .defectTotal .navList .navListRight {
    float: right;
    background:none;
    padding:0;
  }

  .defectTotal .download-file {
    margin:3px 12px 0 25px;
    padding: 7px 8px;
    background: #769dd6;
    border: none;
    font-size: 20px;
    text-align: center;
    cursor: pointer;
  }

  .defectTotal >>> .el-table thead th {
    background: #d3e9bb;
  }

  .defectTotal >>> .el-table thead {
    color: #5d9120;
    text-align: center;
  }

  .el-table-footer {
    background: #d3e9bb
  }

  .el-table-footer li {
    float: left;
  }

  @media screen and (max-width: 1400px) {
    .defectTotal {
      padding: 6px;
    }
  }
</style>
